package red.stu.pconstraint.xml.parser;

import red.stu.pconstraint.parser.GenericTokenParser;
import red.stu.pconstraint.parser.TokenHandler;

import java.util.Properties;

/**
 * PropertyParser
 * @author yihrmc @stu.red
 * @date 2019/11/14 10:56
 */
public class PropertyParser {

    public static String parse(String value, Properties variables) {
        String openToken = variables.getProperty("variableOpenToken", "${");
        String closeToken = variables.getProperty("variableCloseToken", "}");
        return new GenericTokenParser(openToken, closeToken, new VariableTokenHandler(variables)).parse(value);
    }

    private static class VariableTokenHandler implements TokenHandler {

        private final Properties variables;

        private VariableTokenHandler(Properties variables) {
            this.variables = variables;
        }

        @Override
        public String handleToken(String content, String openToken, String closeToken) {
            if (content.startsWith("%") && content.endsWith("%")) {
                return "*******";
            }
            String value = variables.getProperty(content);
            if (value == null) {
                return openToken + content + closeToken;
            }
            return value;
        }

    }

}
